package com.ray.controller.sys;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.ray.controller.base.BaseController;
import com.ray.log.WebLog;
import com.ray.model.DataButton;
import com.ray.model.Menu;
import com.ray.model.Permissions;
import com.ray.services.MenuService;
import com.ray.util.JsonKit;
import com.ray.util.Ret;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 菜单相关处理类
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private PermissionController permissionController;

    @RequestMapping("menus")
    @WebLog(description = "获取菜单列表")
    public Ret menus() {
        List<Record> menu = menuService.getMenus(new Record().set("id", 0));
        if (!user().getIsCoder()) {
            String sql = "SELECT t1.menu_no FROM permissions t1 "
                    + "LEFT JOIN role_permission t2 ON t1.no = t2.permission_no "
                    + "LEFT JOIN user_role t3 ON t2.role_no = t3.role_no WHERE "
                    + "t3.userid = '" + getSessionUserId() + "' AND t1.type = 1";
            List<Record> menuPermissions = Db.use(base).find(sql);
            menu = menuAuth(menu, menuPermissions, null, 0);
        }

        //消息图标红点
        boolean msgNew = false;
//			MsgUser temp = MsgUser.dao.findFirst("select * from msg_user where is_read = 0 and region = ? and userid = ?",getSessionUserRegion(),getSessionUserId());
//			if(temp!=null)
//				msgNew = true;

        return Ret.ok("menus", JsonKit.toJson(menu)).set("msgNew", msgNew);
    }

    /**
     * 递归获取菜单
     *
     * @param menu
     * @return
     */
    public List<Record> getMenus(Record menu) {
        String sql = "select * from menu"
                + " where parent_menu = ? and is_hide = 0";
        sql += " order by seq_num";
        List<Record> children_menu = Db.use(base).find(sql, menu.getInt("id"));
        for (Record children : children_menu) {
            List<Record> temp = getMenus(children);
            children.set("children", temp);
        }
        return children_menu;
    }

    /**
     * 菜单鉴权
     *
     * @param menu
     * @param menuPermissions
     * @param fatherList
     * @param index
     * @return
     */
    public List<Record> menuAuth(List<Record> menu, List<Record> menuPermissions, List<Record> fatherList, int index) {
        for (int i = menu.size() - 1; i >= 0; i--) {
            List<Record> children = (List<Record>) menu.get(i).get("children");
            if (children.size() == 0) {
                boolean flag = true;
                for (int j = 0; j < menuPermissions.size(); j++) {
                    if (menu.get(i).get("no").equals(menuPermissions.get(j).getStr("menu_no"))) {
                        flag = false;
                    }
                }
                if (flag) {
                    menu.remove(i);
                }
            } else {
                menu.get(i).set("children", menuAuth((List<Record>) menu.get(i).get("children"), menuPermissions, menu, i));
            }

        }
        if (menu.size() == 0 && fatherList != null) {
            fatherList.remove(index);
        }
        return menu;
    }

    /**
     * @note 系统设置-菜单管理
     * @time 2024年03月24日 18:56:08
     * @author Ray
     */
    @RequestMapping("getTreeMenu")
    @WebLog(description = "获取菜单树")
    public Ret getTreeMenu() {
        List<Record> result = Db.use(base).find("select * from menu where parent_menu = 0 order by seq_num");
        result = tree(result);
        return Ret.ok("msg", "成功").setJson("list", result);
    }

    public List<Record> tree(List<Record> trees) {
        for (int i = 0; i < trees.size(); i++) {
            List<Record> temp = Db.use(base).find("select * from menu where parent_menu = " + trees.get(i).getInt("id") + " order by seq_num");
            tree(temp);
            trees.get(i).set("list", temp);
        }
        return trees;
    }

    /**
     * @note 新增或修改菜单
     * @time 2024年03月24日 19:02:16
     * @author Ray
     */
    /*@RequestMapping("menuAddOrEdit")
    @CacheEvict(value = "menu", allEntries = true)
    @WebLog(description = "新增或修改菜单")
    @Transactional("baseTransactionManager")
    public Ret menuAddOrEdit(@RequestBody Menu menu) {
            if (menu.getId() != null) {
                menu.update();
            } else {
                Menu temp = Menu.dao.findFirst("select * from menu where no = ?", menu.getNo());
                if (temp != null) {
                    return Ret.ok("当前菜单编号已存在，请勿重复添加");
                }
                menu.setPath(menu.getNo());
                //同步新增权限列表--新增-修改-删除
                //单表
                Permissions p = new Permissions();
                if (menu.getType() == 1) {
                    //单表模型
                    menu.setComponent("/template/single");
                    //查看
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_query").setName("查看").setType(1).setMenuNo(menu.getNo()).save();
                    //新增
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_add").setName("新增").setType(2).setMenuNo(menu.getNo()).save();
                    //修改
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_edit").setName("修改").setType(2).setMenuNo(menu.getNo()).save();
                    //删除
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_del").setName("删除").setType(2).setMenuNo(menu.getNo()).save();
                    List<DataButton> buttons = dataObjectService.getDataButtons(menu.getDataObjectNo());
                    for (DataButton item : buttons) {
                        p.remove("id");
                        p.setNo(menu.getNo() + "_" + item.getPermissionNo()).setName(item.getPermissionName()).setType(2).setMenuNo(menu.getNo()).save();
                    }
                } else if (menu.getType() == 2 || menu.getType() == 3 || menu.getType() == 4) {
                    if (menu.getType() == 2) {
                        //主子表模型
                        menu.setComponent("/template/zz");
                    } else if (menu.getType() == 3) {
                        //树表模型
                        menu.setComponent("/template/tree");
                    } else if (menu.getType() == 4) {
                        //订单模型
                        menu.setComponent("/template/order");
                    }
                    //查看
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_query").setName("查看").setType(1).setMenuNo(menu.getNo()).save();
                    //主表新增
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_add").setName("主表新增").setType(2).setMenuNo(menu.getNo()).save();
                    //主表修改
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_edit").setName("主表修改").setType(2).setMenuNo(menu.getNo()).save();
                    //主表删除
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_del").setName("主表删除").setType(2).setMenuNo(menu.getNo()).save();
                    //子表新增
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getSonDataObjectNo() + "_add").setName("子表新增").setType(2).setMenuNo(menu.getNo()).save();
                    //子表修改
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getSonDataObjectNo() + "_edit").setName("子表修改").setType(2).setMenuNo(menu.getNo()).save();
                    //子表删除
                    p.remove("id");
                    p.setNo(menu.getNo() + "_" + menu.getSonDataObjectNo() + "_del").setName("子表删除").setType(2).setMenuNo(menu.getNo()).save();
                    List<DataButton> buttons = dataObjectService.getDataButtons(menu.getDataObjectNo());
                    for (DataButton item : buttons) {
                        p.remove("id");
                        p.setNo(menu.getNo() + "_" + item.getPermissionNo()).setName(item.getPermissionName()).setType(2).setMenuNo(menu.getNo()).save();
                    }
                } else {
                    menu.setComponent(menu.getComponent() == null ? (menu.getParentMenu() == 0 ? "#" : "##") : menu.getComponent());
                }
                menu.save();
            }
            return Ret.ok("新增或修改菜单成功");
    }*/
    @RequestMapping("menuAddOrEdit")
    @CacheEvict(value = "menu", allEntries = true)
    @WebLog(description = "新增或修改菜单")
    @Transactional("baseTransactionManager")
    public Ret menuAddOrEdit(@RequestBody Menu menu) {
        if (menu.getId() != null) {
            menu.update();
        } else {
            Menu temp = Menu.dao.findFirst("select * from menu where no = ?", menu.getNo());
            if (temp != null) {
                return Ret.ok("当前菜单编号已存在，请勿重复添加");
            }
            menu.setPath(menu.getNo());
            if (menu.getType() == 1) {
                //单表模型
                menu.setComponent("/template/single");
            } else if (menu.getType() == 2 || menu.getType() == 3 || menu.getType() == 4) {
                if (menu.getType() == 2) {
                    //主子表模型
                    menu.setComponent("/template/zz");
                } else if (menu.getType() == 3) {
                    //树表模型
                    menu.setComponent("/template/tree");
                } else if (menu.getType() == 4) {
                    //订单模型
                    menu.setComponent("/template/order");
                }
            } else {
                menu.setComponent(menu.getComponent() == null ? (menu.getParentMenu() == 0 ? "#" : "##") : menu.getComponent());
            }
            //添加当前菜单所有的增删改查权限列表
            permissionController.addPermission(menu);
            menu.save();
        }
        return Ret.ok("新增或修改菜单成功");
    }

    /**
     * @note 删除菜单及下级菜单（包括与之关联的权限）
     * @time 2024年03月24日 19:24:26
     * @author Ray
     */
    @RequestMapping("delMenu")
    @CacheEvict(value = "menu", allEntries = true)
    @WebLog(description = "")
    @Transactional("baseTransactionManager")
    public Ret delMenu(int id) {
        deleteMenu(id, getSessionUserRegion());
        return Ret.ok("msg", "删除菜单及子菜单成功");
    }

    public void deleteMenu(int parent_menu, String region) {
        Menu menu = Menu.dao.findById(parent_menu);
        List<Menu> sonMenus = Menu.dao.find("select * from menu where parent_menu = " + parent_menu);
        for (int i = 0; i < sonMenus.size(); i++) {
            deleteMenu(sonMenus.get(i).getId(), region);
        }
        List<Permissions> list = Permissions.dao.find("select * from permissions where menu_no = ?", menu.getNo());
        for (Permissions item : list) {
            Db.use(base).delete("delete from role_permission "
                    + "where permission_no = ? and region = ?", item.getNo(), getSessionUserRegion());
            item.delete();
        }
        menu.delete();
    }
}
